package com.ruoyi.jdbc.service.impl;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.jdbc.config.MySqlOrderShardTableEnsurer;
import com.ruoyi.jdbc.domain.Order;
import com.ruoyi.jdbc.mapper.OrderMapper;
import com.ruoyi.jdbc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MySqlOrderShardTableEnsurer tableEnsurer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insert(Order o) {
        // 1) 业务侧保证分片键不为空
        if (o.getCreateTime() == null) {
            o.setCreateTime(LocalDateTime.now());
        }
        if (o.getUpdateTime() == null) {
            o.setUpdateTime(o.getCreateTime());
        }

        // 2) 先确保对应月份表存在（DDL）
        tableEnsurer.ensureByCreateTime(o.getCreateTime());
        orderMapper.insert(o);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult queryById(Long id) {
        Order order = orderMapper.findById(id);
        return AjaxResult.success( order);
    }

    @Override
    public AjaxResult queryByTime(LocalDateTime start, LocalDateTime end) {
        List<Order> orders = orderMapper.queryByTime(start, end);
        return AjaxResult.success( orders);
    }
}
